package com.briup.cms.log;

import com.briup.cms.bean.BaseLog;
import com.briup.cms.utils.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志注解LoggingAccess的解析类
 */
@Aspect
public class LoggingAccessAspectResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAccessAspectResolver.class);

    private LoggingAccessPersisting loggingAccessPersisting;

    public LoggingAccessAspectResolver(LoggingAccessPersisting loggingAccessPersisting) {
        this.loggingAccessPersisting = loggingAccessPersisting;
    }

//    @Pointcut("within(com.briup..web.contoller..*)")
//    @Pointcut("within(com.briup..web.contoller..*)")
    @Pointcut("execution(* com.briup.cms.web.controller.*.*(..)) && @annotation(LoggingAccess)")
    public void loggingPoincut() {
    }

    // 环绕拦截器
    @Around("loggingPoincut()")
    public Object loggingAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature methodSignature = ((MethodSignature) proceedingJoinPoint.getSignature());
        Method method = methodSignature.getMethod();

        BaseLog log = new BaseLog();

        //设置当前用户的信息
        setloggingInfo(log);

        try {
            loggingAccessPersisting.persist(log);
        } catch (Exception exception) {
            LOGGER.error("An exception[{}] occurred while saving the log", exception);
        }

        return proceedingJoinPoint.proceed();

    }


    // 封装log日志的详细信息
    private void setloggingInfo(BaseLog log) {

        log.setLogUsername(SecurityUtils.getUsername());
        log.setLogRealname(SecurityUtils.getRealname());
        log.setLogRequestMethod(SecurityUtils.getmethod());
        log.setLogRequestUri(SecurityUtils.getRequestURI());
        log.setLogTime(new Date());

    }


}
